########################################################################
#  Wiizard - A Wii games manager
#  Copyright (C) 2023  CYBERDEViL
#
#  This file is part of Wiizard.
#
#  Wiizard is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Wiizard is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################


from PyQt5.QtWidgets import (
  QDialog,
  QListWidget,
  QGridLayout,
  QLabel,
  QPushButton,
  QCheckBox,
  QMessageBox
)

import pywwt

from wiizard.source import PartitionRepairThread
import wiizard.globals as Global
from wiizard.translations import _

"""
 _________[REPAIR]___________

  Partition: /dev/sdb1
  Errors   : 1783

  ________Summary_______
 |...                   |
 |....                  |
 |..                    |
 |______________________|

 [X] Simulate

 [Cancel] [Repair]
"""


class RepairDialog(QDialog):
  def __init__(self, sourceModel, parent=None):
    QDialog.__init__(self, parent=parent)
    self.__sourceModel  = sourceModel
    self.__repairThread = None

    self.setWindowTitle(_("Repair partition"))

    layout = QGridLayout(self)

    layout.addWidget(QLabel(_("Partition:"), self), 0, 0, 1, 1)
    layout.addWidget(QLabel(sourceModel.location, self), 0, 1, 1, 1)

    layout.addWidget(QLabel(_("Errors:"), self), 1, 0, 1, 1)
    layout.addWidget(QLabel(str(sourceModel.hasErrors()), self), 1, 1, 1, 1)

    self.__errorsList = QListWidget(self)
    for errorMessage in sourceModel.getErrors():
      self.__errorsList.addItem(errorMessage)
    layout.addWidget(self.__errorsList, 2, 0, 1, 2)

    self.__simulateCheck = QCheckBox(_("Simulate"), self)
    self.__simulateCheck.setChecked(True)
    layout.addWidget(self.__simulateCheck, 3, 0, 1, 2)

    self.__cancelButton = QPushButton(_("Cancel"), self)
    self.__repairButton = QPushButton(_("Repair"), self)
    layout.addWidget(self.__cancelButton, 4, 0, 1, 1)
    layout.addWidget(self.__repairButton, 4, 1, 1, 1)

    self.__cancelButton.clicked.connect(self.reject)
    self.__repairButton.clicked.connect(self.__onRepairClicked)

  def __onRepairClicked(self):
    testMode = True
    if not self.__simulateCheck.isChecked():
      r = QMessageBox.question(self, _("Continue?"),
                               _("You can lose your data when anything goes "
                               "wrong, do you want to continue?"))
      if r != QMessageBox.Yes:
        return
      testMode = False
    self.startRepair(testMode=testMode)

  def startRepair(self, repairMode=pywwt.REPAIR_ALL, testMode=True):
    if self.__repairThread is not None:
      print("PartitionSourceModel Already repairing .. FIXME this should not "
            "happen! Please report.")
      return

    self.__repairThread = PartitionRepairThread(
      self.__sourceModel.location,
      repairMode=repairMode,
      testMode=testMode)
    self.__repairThread.completed.connect(self.__onRepairComplete)
    Global.ActiveThreads.append(self.__repairThread)
    self.__repairThread.start()

  def __onRepairComplete(self):
    self.__repairThread.wait()
    Global.ActiveThreads.remove(self.__repairThread)

    message = None
    if self.__repairThread.result:
      QMessageBox.information(self, _("Repair result"),
                              _("Repair successfull!"))
    else:
      QMessageBox.critical(self, _("Repair result"),
                           _(f"Repair failed! {self.__repairThread.error}"))

    self.__repairThread.quit()
    self.__repairThread = None
